import { defineStore } from 'pinia';
import axios from 'axios';
import { TokenUtil } from '@/utils/common.js'
import { StorageUtil } from '@/utils/common.js'
import router from '@/router'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
    isLoading: false,
    error: null,
  }),
  actions: {
    async login(credentials) {
      this.isLoading = true;
      this.error = null;
      try {
        const response = await axios.post('/api/login', credentials);
        this.user = response.data.user;
        this.token = response.data.token;
        TokenUtil.setToken(this.token);
        StorageUtil.local.set('userInfo', response.data.user);
        ElMessage.success('登录成功')
        router.push('/');
      } catch (error) {
        this.error = error.response ? error.response.data.message : error.message;
      } finally {
        this.isLoading = false;
      }
    },
    logout() {
      this.user = null
      this.token = null;
      TokenUtil.removeToken();
      StorageUtil.local.remove('access_token')
      StorageUtil.local.remove('user')
      StorageUtil.session.clear()
      router.push('/login');
    },
  },
}); 